import { User } from "./model";
import express, { Request, Response, NextFunction } from "express";
import BookRouter from './routes/book';
import CategoryRouter from './routes/category';
import UserRouter from './routes/users';
import IndexRouter from './routes/index';
var createError = require('http-errors');
import { expressjwt } from "express-jwt";
import { SECRET_KEY } from "./constant";

var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var req = require('express/lib/request');
require('./model/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'jade');

app.get('/', (req: any, res: any) => {
  const userModel = new User({ name: 'unicorn', nickname: 'unicorn' })
  userModel.save();
  res.json({ success: true })
})


app.use(expressjwt({ secret: SECRET_KEY, algorithms: ['HS256'] }).unless({
  path: ['/api/users/login']
}))

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/books', BookRouter)
app.use('/api/categories', CategoryRouter)
app.use('/api/users', UserRouter)
app.use('/api/index', IndexRouter)
// catch 404 and forward to error handler
app.use(function (req: Request, res: Response, next: NextFunction) {
  next(createError(404));
});

// error handler
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen('3005', () => {
  console.log('listening on http://localhost: 3005')
})

module.exports = app;
